home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / imaplib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  45KB  |  1,403 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''IMAP4 client.
  5.  
  6. Based on RFC 2060.
  7.  
  8. Public class:           IMAP4
  9. Public variable:        Debug
  10. Public functions:       Internaldate2tuple
  11.                         Int2AP
  12.                         ParseFlags
  13.                         Time2Internaldate
  14. '''
  15. __version__ = '2.58'
  16. import binascii
  17. import os
  18. import random
  19. import re
  20. import socket
  21. import sys
  22. import time
  23. __all__ = [
  24.     'IMAP4',
  25.     'IMAP4_stream',
  26.     'Internaldate2tuple',
  27.     'Int2AP',
  28.     'ParseFlags',
  29.     'Time2Internaldate']
  30. CRLF = '\r\n'
  31. Debug = 0
  32. IMAP4_PORT = 143
  33. IMAP4_SSL_PORT = 993
  34. AllowedVersions = ('IMAP4REV1', 'IMAP4')
  35. Commands = {
  36.     'APPEND': ('AUTH', 'SELECTED'),
  37.     'AUTHENTICATE': ('NONAUTH',),
  38.     'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  39.     'CHECK': ('SELECTED',),
  40.     'CLOSE': ('SELECTED',),
  41.     'COPY': ('SELECTED',),
  42.     'CREATE': ('AUTH', 'SELECTED'),
  43.     'DELETE': ('AUTH', 'SELECTED'),
  44.     'DELETEACL': ('AUTH', 'SELECTED'),
  45.     'EXAMINE': ('AUTH', 'SELECTED'),
  46.     'EXPUNGE': ('SELECTED',),
  47.     'FETCH': ('SELECTED',),
  48.     'GETACL': ('AUTH', 'SELECTED'),
  49.     'GETANNOTATION': ('AUTH', 'SELECTED'),
  50.     'GETQUOTA': ('AUTH', 'SELECTED'),
  51.     'GETQUOTAROOT': ('AUTH', 'SELECTED'),
  52.     'MYRIGHTS': ('AUTH', 'SELECTED'),
  53.     'LIST': ('AUTH', 'SELECTED'),
  54.     'LOGIN': ('NONAUTH',),
  55.     'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  56.     'LSUB': ('AUTH', 'SELECTED'),
  57.     'NAMESPACE': ('AUTH', 'SELECTED'),
  58.     'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  59.     'PARTIAL': ('SELECTED',),
  60.     'PROXYAUTH': ('AUTH',),
  61.     'RENAME': ('AUTH', 'SELECTED'),
  62.     'SEARCH': ('SELECTED',),
  63.     'SELECT': ('AUTH', 'SELECTED'),
  64.     'SETACL': ('AUTH', 'SELECTED'),
  65.     'SETANNOTATION': ('AUTH', 'SELECTED'),
  66.     'SETQUOTA': ('AUTH', 'SELECTED'),
  67.     'SORT': ('SELECTED',),
  68.     'STATUS': ('AUTH', 'SELECTED'),
  69.     'STORE': ('SELECTED',),
  70.     'SUBSCRIBE': ('AUTH', 'SELECTED'),
  71.     'THREAD': ('SELECTED',),
  72.     'UID': ('SELECTED',),
  73.     'UNSUBSCRIBE': ('AUTH', 'SELECTED') }
  74. Continuation = re.compile('\\+( (?P<data>.*))?')
  75. Flags = re.compile('.*FLAGS \\((?P<flags>[^\\)]*)\\)')
  76. InternalDate = re.compile('.*INTERNALDATE "(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9]) (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9]) (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])"')
  77. Literal = re.compile('.*{(?P<size>\\d+)}$')
  78. MapCRLF = re.compile('\\r\\n|\\r|\\n')
  79. Response_code = re.compile('\\[(?P<type>[A-Z-]+)( (?P<data>[^\\]]*))?\\]')
  80. Untagged_response = re.compile('\\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  81. Untagged_status = re.compile('\\* (?P<data>\\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
  82.  
  83. class IMAP4:
  84.     '''IMAP4 client class.
  85.  
  86.     Instantiate with: IMAP4([host[, port]])
  87.  
  88.             host - host\'s name (default: localhost);
  89.             port - port number (default: standard IMAP4 port).
  90.  
  91.     All IMAP4rev1 commands are supported by methods of the same
  92.     name (in lower-case).
  93.  
  94.     All arguments to commands are converted to strings, except for
  95.     AUTHENTICATE, and the last argument to APPEND which is passed as
  96.     an IMAP4 literal.  If necessary (the string contains any
  97.     non-printing characters or white-space and isn\'t enclosed with
  98.     either parentheses or double quotes) each string is quoted.
  99.     However, the \'password\' argument to the LOGIN command is always
  100.     quoted.  If you want to avoid having an argument string quoted
  101.     (eg: the \'flags\' argument to STORE) then enclose the string in
  102.     parentheses (eg: "(\\Deleted)").
  103.  
  104.     Each command returns a tuple: (type, [data, ...]) where \'type\'
  105.     is usually \'OK\' or \'NO\', and \'data\' is either the text from the
  106.     tagged response, or untagged results from command. Each \'data\'
  107.     is either a string, or a tuple. If a tuple, then the first part
  108.     is the header of the response, and the second part contains
  109.     the data (ie: \'literal\' value).
  110.  
  111.     Errors raise the exception class <instance>.error("<reason>").
  112.     IMAP4 server errors raise <instance>.abort("<reason>"),
  113.     which is a sub-class of \'error\'. Mailbox status changes
  114.     from READ-WRITE to READ-ONLY raise the exception class
  115.     <instance>.readonly("<reason>"), which is a sub-class of \'abort\'.
  116.  
  117.     "error" exceptions imply a program error.
  118.     "abort" exceptions imply the connection should be reset, and
  119.             the command re-tried.
  120.     "readonly" exceptions imply the command should be re-tried.
  121.  
  122.     Note: to use this module, you must read the RFCs pertaining to the
  123.     IMAP4 protocol, as the semantics of the arguments to each IMAP4
  124.     command are left to the invoker, not to mention the results. Also,
  125.     most IMAP servers implement a sub-set of the commands available here.
  126.     '''
  127.     
  128.     class error(Exception):
  129.         pass
  130.  
  131.     
  132.     class abort(error):
  133.         pass
  134.  
  135.     
  136.     class readonly(abort):
  137.         pass
  138.  
  139.     mustquote = re.compile("[^\\w!#$%&'*+,.:;<=>?^`|~-]")
  140.     
  141.     def __init__(self, host = '', port = IMAP4_PORT):
  142.         self.debug = Debug
  143.         self.state = 'LOGOUT'
  144.         self.literal = None
  145.         self.tagged_commands = { }
  146.         self.untagged_responses = { }
  147.         self.continuation_response = ''
  148.         self.is_readonly = False
  149.         self.tagnum = 0
  150.         self.open(host, port)
  151.         self.tagpre = Int2AP(random.randint(4096, 65535))
  152.         self.tagre = re.compile('(?P<tag>' + self.tagpre + '\\d+) (?P<type>[A-Z]+) (?P<data>.*)')
  153.         self._cmd_log_len = 10
  154.         self._cmd_log_idx = 0
  155.         self._cmd_log = { }
  156.         if self.debug >= 1:
  157.             self._mesg('imaplib version %s' % __version__)
  158.             self._mesg('new IMAP4 connection, tag=%s' % self.tagpre)
  159.         
  160.         self.welcome = self._get_response()
  161.         if 'PREAUTH' in self.untagged_responses:
  162.             self.state = 'AUTH'
  163.         elif 'OK' in self.untagged_responses:
  164.             self.state = 'NONAUTH'
  165.         else:
  166.             raise self.error(self.welcome)
  167.         (typ, dat) = ('PREAUTH' in self.untagged_responses).capability()
  168.         if dat == [
  169.             None]:
  170.             raise self.error('no CAPABILITY response from server')
  171.         dat == [
  172.             None]
  173.         self.capabilities = tuple(dat[-1].upper().split())
  174.         if self.debug >= 3:
  175.             self._mesg('CAPABILITIES: %r' % (self.capabilities,))
  176.         
  177.         for version in AllowedVersions:
  178.             if version not in self.capabilities:
  179.                 continue
  180.             
  181.             self.PROTOCOL_VERSION = version
  182.             return None
  183.         
  184.         raise self.error('server not IMAP4 compliant')
  185.  
  186.     
  187.     def __getattr__(self, attr):
  188.         if attr in Commands:
  189.             return getattr(self, attr.lower())
  190.         raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  191.  
  192.     
  193.     def open(self, host = '', port = IMAP4_PORT):
  194.         '''Setup connection to remote server on "host:port"
  195.             (default: localhost:standard IMAP4 port).
  196.         This connection will be used by the routines:
  197.             read, readline, send, shutdown.
  198.         '''
  199.         self.host = host
  200.         self.port = port
  201.         self.sock = socket.create_connection((host, port))
  202.         self.file = self.sock.makefile('rb')
  203.  
  204.     
  205.     def read(self, size):
  206.         """Read 'size' bytes from remote."""
  207.         return self.file.read(size)
  208.  
  209.     
  210.     def readline(self):
  211.         '''Read line from remote.'''
  212.         return self.file.readline()
  213.  
  214.     
  215.     def send(self, data):
  216.         '''Send data to remote.'''
  217.         self.sock.sendall(data)
  218.  
  219.     
  220.     def shutdown(self):
  221.         '''Close I/O established in "open".'''
  222.         self.file.close()
  223.         self.sock.close()
  224.  
  225.     
  226.     def socket(self):
  227.         '''Return socket instance used to connect to IMAP4 server.
  228.  
  229.         socket = <instance>.socket()
  230.         '''
  231.         return self.sock
  232.  
  233.     
  234.     def recent(self):
  235.         """Return most recent 'RECENT' responses if any exist,
  236.         else prompt server for an update using the 'NOOP' command.
  237.  
  238.         (typ, [data]) = <instance>.recent()
  239.  
  240.         'data' is None if no new messages,
  241.         else list of RECENT responses, most recent last.
  242.         """
  243.         name = 'RECENT'
  244.         (typ, dat) = self._untagged_response('OK', [
  245.             None], name)
  246.         if dat[-1]:
  247.             return (typ, dat)
  248.         (typ, dat) = self.noop()
  249.         return self._untagged_response(typ, dat, name)
  250.  
  251.     
  252.     def response(self, code):
  253.         """Return data for response 'code' if received, or None.
  254.  
  255.         Old value for response 'code' is cleared.
  256.  
  257.         (code, [data]) = <instance>.response(code)
  258.         """
  259.         return self._untagged_response(code, [
  260.             None], code.upper())
  261.  
  262.     
  263.     def append(self, mailbox, flags, date_time, message):
  264.         """Append message to named mailbox.
  265.  
  266.         (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
  267.  
  268.                 All args except `message' can be None.
  269.         """
  270.         name = 'APPEND'
  271.         if not mailbox:
  272.             mailbox = 'INBOX'
  273.         
  274.         if flags:
  275.             if (flags[0], flags[-1]) != ('(', ')'):
  276.                 flags = '(%s)' % flags
  277.             
  278.         else:
  279.             flags = None
  280.         if date_time:
  281.             date_time = Time2Internaldate(date_time)
  282.         else:
  283.             date_time = None
  284.         self.literal = MapCRLF.sub(CRLF, message)
  285.         return self._simple_command(name, mailbox, flags, date_time)
  286.  
  287.     
  288.     def authenticate(self, mechanism, authobject):
  289.         """Authenticate command - requires response processing.
  290.  
  291.         'mechanism' specifies which authentication mechanism is to
  292.         be used - it must appear in <instance>.capabilities in the
  293.         form AUTH=<mechanism>.
  294.  
  295.         'authobject' must be a callable object:
  296.  
  297.                 data = authobject(response)
  298.  
  299.         It will be called to process server continuation responses.
  300.         It should return data that will be encoded and sent to server.
  301.         It should return None if the client abort response '*' should
  302.         be sent instead.
  303.         """
  304.         mech = mechanism.upper()
  305.         self.literal = _Authenticator(authobject).process
  306.         (typ, dat) = self._simple_command('AUTHENTICATE', mech)
  307.         if typ != 'OK':
  308.             raise self.error(dat[-1])
  309.         typ != 'OK'
  310.         self.state = 'AUTH'
  311.         return (typ, dat)
  312.  
  313.     
  314.     def capability(self):
  315.         '''(typ, [data]) = <instance>.capability()
  316.         Fetch capabilities list from server.'''
  317.         name = 'CAPABILITY'
  318.         (typ, dat) = self._simple_command(name)
  319.         return self._untagged_response(typ, dat, name)
  320.  
  321.     
  322.     def check(self):
  323.         '''Checkpoint mailbox on server.
  324.  
  325.         (typ, [data]) = <instance>.check()
  326.         '''
  327.         return self._simple_command('CHECK')
  328.  
  329.     
  330.     def close(self):
  331.         """Close currently selected mailbox.
  332.  
  333.         Deleted messages are removed from writable mailbox.
  334.         This is the recommended command before 'LOGOUT'.
  335.  
  336.         (typ, [data]) = <instance>.close()
  337.         """
  338.         
  339.         try:
  340.             (typ, dat) = self._simple_command('CLOSE')
  341.         finally:
  342.             self.state = 'AUTH'
  343.  
  344.         return (typ, dat)
  345.  
  346.     
  347.     def copy(self, message_set, new_mailbox):
  348.         """Copy 'message_set' messages onto end of 'new_mailbox'.
  349.  
  350.         (typ, [data]) = <instance>.copy(message_set, new_mailbox)
  351.         """
  352.         return self._simple_command('COPY', message_set, new_mailbox)
  353.  
  354.     
  355.     def create(self, mailbox):
  356.         '''Create new mailbox.
  357.  
  358.         (typ, [data]) = <instance>.create(mailbox)
  359.         '''
  360.         return self._simple_command('CREATE', mailbox)
  361.  
  362.     
  363.     def delete(self, mailbox):
  364.         '''Delete old mailbox.
  365.  
  366.         (typ, [data]) = <instance>.delete(mailbox)
  367.         '''
  368.         return self._simple_command('DELETE', mailbox)
  369.  
  370.     
  371.     def deleteacl(self, mailbox, who):
  372.         '''Delete the ACLs (remove any rights) set for who on mailbox.
  373.  
  374.         (typ, [data]) = <instance>.deleteacl(mailbox, who)
  375.         '''
  376.         return self._simple_command('DELETEACL', mailbox, who)
  377.  
  378.     
  379.     def expunge(self):
  380.         """Permanently remove deleted items from selected mailbox.
  381.  
  382.         Generates 'EXPUNGE' response for each deleted message.
  383.  
  384.         (typ, [data]) = <instance>.expunge()
  385.  
  386.         'data' is list of 'EXPUNGE'd message numbers in order received.
  387.         """
  388.         name = 'EXPUNGE'
  389.         (typ, dat) = self._simple_command(name)
  390.         return self._untagged_response(typ, dat, name)
  391.  
  392.     
  393.     def fetch(self, message_set, message_parts):
  394.         '''Fetch (parts of) messages.
  395.  
  396.         (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
  397.  
  398.         \'message_parts\' should be a string of selected parts
  399.         enclosed in parentheses, eg: "(UID BODY[TEXT])".
  400.  
  401.         \'data\' are tuples of message part envelope and data.
  402.         '''
  403.         name = 'FETCH'
  404.         (typ, dat) = self._simple_command(name, message_set, message_parts)
  405.         return self._untagged_response(typ, dat, name)
  406.  
  407.     
  408.     def getacl(self, mailbox):
  409.         '''Get the ACLs for a mailbox.
  410.  
  411.         (typ, [data]) = <instance>.getacl(mailbox)
  412.         '''
  413.         (typ, dat) = self._simple_command('GETACL', mailbox)
  414.         return self._untagged_response(typ, dat, 'ACL')
  415.  
  416.     
  417.     def getannotation(self, mailbox, entry, attribute):
  418.         '''(typ, [data]) = <instance>.getannotation(mailbox, entry, attribute)
  419.         Retrieve ANNOTATIONs.'''
  420.         (typ, dat) = self._simple_command('GETANNOTATION', mailbox, entry, attribute)
  421.         return self._untagged_response(typ, dat, 'ANNOTATION')
  422.  
  423.     
  424.     def getquota(self, root):
  425.         """Get the quota root's resource usage and limits.
  426.  
  427.         Part of the IMAP4 QUOTA extension defined in rfc2087.
  428.  
  429.         (typ, [data]) = <instance>.getquota(root)
  430.         """
  431.         (typ, dat) = self._simple_command('GETQUOTA', root)
  432.         return self._untagged_response(typ, dat, 'QUOTA')
  433.  
  434.     
  435.     def getquotaroot(self, mailbox):
  436.         '''Get the list of quota roots for the named mailbox.
  437.  
  438.         (typ, [[QUOTAROOT responses...], [QUOTA responses]]) = <instance>.getquotaroot(mailbox)
  439.         '''
  440.         (typ, dat) = self._simple_command('GETQUOTAROOT', mailbox)
  441.         (typ, quota) = self._untagged_response(typ, dat, 'QUOTA')
  442.         (typ, quotaroot) = self._untagged_response(typ, dat, 'QUOTAROOT')
  443.         return (typ, [
  444.             quotaroot,
  445.             quota])
  446.  
  447.     
  448.     def list(self, directory = '""', pattern = '*'):
  449.         '''List mailbox names in directory matching pattern.
  450.  
  451.         (typ, [data]) = <instance>.list(directory=\'""\', pattern=\'*\')
  452.  
  453.         \'data\' is list of LIST responses.
  454.         '''
  455.         name = 'LIST'
  456.         (typ, dat) = self._simple_command(name, directory, pattern)
  457.         return self._untagged_response(typ, dat, name)
  458.  
  459.     
  460.     def login(self, user, password):
  461.         """Identify client using plaintext password.
  462.  
  463.         (typ, [data]) = <instance>.login(user, password)
  464.  
  465.         NB: 'password' will be quoted.
  466.         """
  467.         (typ, dat) = self._simple_command('LOGIN', user, self._quote(password))
  468.         if typ != 'OK':
  469.             raise self.error(dat[-1])
  470.         typ != 'OK'
  471.         self.state = 'AUTH'
  472.         return (typ, dat)
  473.  
  474.     
  475.     def login_cram_md5(self, user, password):
  476.         ''' Force use of CRAM-MD5 authentication.
  477.  
  478.         (typ, [data]) = <instance>.login_cram_md5(user, password)
  479.         '''
  480.         self.user = user
  481.         self.password = password
  482.         return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH)
  483.  
  484.     
  485.     def _CRAM_MD5_AUTH(self, challenge):
  486.         ''' Authobject to use with CRAM-MD5 authentication. '''
  487.         import hmac as hmac
  488.         return self.user + ' ' + hmac.HMAC(self.password, challenge).hexdigest()
  489.  
  490.     
  491.     def logout(self):
  492.         """Shutdown connection to server.
  493.  
  494.         (typ, [data]) = <instance>.logout()
  495.  
  496.         Returns server 'BYE' response.
  497.         """
  498.         self.state = 'LOGOUT'
  499.         
  500.         try:
  501.             (typ, dat) = self._simple_command('LOGOUT')
  502.         except:
  503.             typ = 'NO'
  504.             dat = [
  505.                 '%s: %s' % sys.exc_info()[:2]]
  506.  
  507.         self.shutdown()
  508.         if 'BYE' in self.untagged_responses:
  509.             return ('BYE', self.untagged_responses['BYE'])
  510.         return (typ, dat)
  511.  
  512.     
  513.     def lsub(self, directory = '""', pattern = '*'):
  514.         '''List \'subscribed\' mailbox names in directory matching pattern.
  515.  
  516.         (typ, [data, ...]) = <instance>.lsub(directory=\'""\', pattern=\'*\')
  517.  
  518.         \'data\' are tuples of message part envelope and data.
  519.         '''
  520.         name = 'LSUB'
  521.         (typ, dat) = self._simple_command(name, directory, pattern)
  522.         return self._untagged_response(typ, dat, name)
  523.  
  524.     
  525.     def myrights(self, mailbox):
  526.         '''Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
  527.  
  528.         (typ, [data]) = <instance>.myrights(mailbox)
  529.         '''
  530.         (typ, dat) = self._simple_command('MYRIGHTS', mailbox)
  531.         return self._untagged_response(typ, dat, 'MYRIGHTS')
  532.  
  533.     
  534.     def namespace(self):
  535.         ''' Returns IMAP namespaces ala rfc2342
  536.  
  537.         (typ, [data, ...]) = <instance>.namespace()
  538.         '''
  539.         name = 'NAMESPACE'
  540.         (typ, dat) = self._simple_command(name)
  541.         return self._untagged_response(typ, dat, name)
  542.  
  543.     
  544.     def noop(self):
  545.         '''Send NOOP command.
  546.  
  547.         (typ, [data]) = <instance>.noop()
  548.         '''
  549.         if self.debug >= 3:
  550.             self._dump_ur(self.untagged_responses)
  551.         
  552.         return self._simple_command('NOOP')
  553.  
  554.     
  555.     def partial(self, message_num, message_part, start, length):
  556.         """Fetch truncated part of a message.
  557.  
  558.         (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
  559.  
  560.         'data' is tuple of message part envelope and data.
  561.         """
  562.         name = 'PARTIAL'
  563.         (typ, dat) = self._simple_command(name, message_num, message_part, start, length)
  564.         return self._untagged_response(typ, dat, 'FETCH')
  565.  
  566.     
  567.     def proxyauth(self, user):
  568.         '''Assume authentication as "user".
  569.  
  570.         Allows an authorised administrator to proxy into any user\'s
  571.         mailbox.
  572.  
  573.         (typ, [data]) = <instance>.proxyauth(user)
  574.         '''
  575.         name = 'PROXYAUTH'
  576.         return self._simple_command('PROXYAUTH', user)
  577.  
  578.     
  579.     def rename(self, oldmailbox, newmailbox):
  580.         '''Rename old mailbox name to new.
  581.  
  582.         (typ, [data]) = <instance>.rename(oldmailbox, newmailbox)
  583.         '''
  584.         return self._simple_command('RENAME', oldmailbox, newmailbox)
  585.  
  586.     
  587.     def search(self, charset, *criteria):
  588.         """Search mailbox for matching messages.
  589.  
  590.         (typ, [data]) = <instance>.search(charset, criterion, ...)
  591.  
  592.         'data' is space separated list of matching message numbers.
  593.         """
  594.         name = 'SEARCH'
  595.         if charset:
  596.             (typ, dat) = self._simple_command(name, 'CHARSET', charset, *criteria)
  597.         else:
  598.             (typ, dat) = self._simple_command(name, *criteria)
  599.         return self._untagged_response(typ, dat, name)
  600.  
  601.     
  602.     def select(self, mailbox = 'INBOX', readonly = False):
  603.         """Select a mailbox.
  604.  
  605.         Flush all untagged responses.
  606.  
  607.         (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=False)
  608.  
  609.         'data' is count of messages in mailbox ('EXISTS' response).
  610.  
  611.         Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
  612.         other responses should be obtained via <instance>.response('FLAGS') etc.
  613.         """
  614.         self.untagged_responses = { }
  615.         self.is_readonly = readonly
  616.         if readonly:
  617.             name = 'EXAMINE'
  618.         else:
  619.             name = 'SELECT'
  620.         (typ, dat) = self._simple_command(name, mailbox)
  621.         if typ != 'OK':
  622.             self.state = 'AUTH'
  623.             return (typ, dat)
  624.         self.state = 'SELECTED'
  625.         if 'READ-ONLY' in self.untagged_responses and not readonly:
  626.             if self.debug >= 1:
  627.                 self._dump_ur(self.untagged_responses)
  628.             
  629.             raise self.readonly('%s is not writable' % mailbox)
  630.         not readonly
  631.         return (typ, self.untagged_responses.get('EXISTS', [
  632.             None]))
  633.  
  634.     
  635.     def setacl(self, mailbox, who, what):
  636.         '''Set a mailbox acl.
  637.  
  638.         (typ, [data]) = <instance>.setacl(mailbox, who, what)
  639.         '''
  640.         return self._simple_command('SETACL', mailbox, who, what)
  641.  
  642.     
  643.     def setannotation(self, *args):
  644.         '''(typ, [data]) = <instance>.setannotation(mailbox[, entry, attribute]+)
  645.         Set ANNOTATIONs.'''
  646.         (typ, dat) = self._simple_command('SETANNOTATION', *args)
  647.         return self._untagged_response(typ, dat, 'ANNOTATION')
  648.  
  649.     
  650.     def setquota(self, root, limits):
  651.         """Set the quota root's resource limits.
  652.  
  653.         (typ, [data]) = <instance>.setquota(root, limits)
  654.         """
  655.         (typ, dat) = self._simple_command('SETQUOTA', root, limits)
  656.         return self._untagged_response(typ, dat, 'QUOTA')
  657.  
  658.     
  659.     def sort(self, sort_criteria, charset, *search_criteria):
  660.         '''IMAP4rev1 extension SORT command.
  661.  
  662.         (typ, [data]) = <instance>.sort(sort_criteria, charset, search_criteria, ...)
  663.         '''
  664.         name = 'SORT'
  665.         if (sort_criteria[0], sort_criteria[-1]) != ('(', ')'):
  666.             sort_criteria = '(%s)' % sort_criteria
  667.         
  668.         (typ, dat) = self._simple_command(name, sort_criteria, charset, *search_criteria)
  669.         return self._untagged_response(typ, dat, name)
  670.  
  671.     
  672.     def status(self, mailbox, names):
  673.         '''Request named status conditions for mailbox.
  674.  
  675.         (typ, [data]) = <instance>.status(mailbox, names)
  676.         '''
  677.         name = 'STATUS'
  678.         (typ, dat) = self._simple_command(name, mailbox, names)
  679.         return self._untagged_response(typ, dat, name)
  680.  
  681.     
  682.     def store(self, message_set, command, flags):
  683.         '''Alters flag dispositions for messages in mailbox.
  684.  
  685.         (typ, [data]) = <instance>.store(message_set, command, flags)
  686.         '''
  687.         if (flags[0], flags[-1]) != ('(', ')'):
  688.             flags = '(%s)' % flags
  689.         
  690.         (typ, dat) = self._simple_command('STORE', message_set, command, flags)
  691.         return self._untagged_response(typ, dat, 'FETCH')
  692.  
  693.     
  694.     def subscribe(self, mailbox):
  695.         '''Subscribe to new mailbox.
  696.  
  697.         (typ, [data]) = <instance>.subscribe(mailbox)
  698.         '''
  699.         return self._simple_command('SUBSCRIBE', mailbox)
  700.  
  701.     
  702.     def thread(self, threading_algorithm, charset, *search_criteria):
  703.         '''IMAPrev1 extension THREAD command.
  704.  
  705.         (type, [data]) = <instance>.thread(threading_alogrithm, charset, search_criteria, ...)
  706.         '''
  707.         name = 'THREAD'
  708.         (typ, dat) = self._simple_command(name, threading_algorithm, charset, *search_criteria)
  709.         return self._untagged_response(typ, dat, name)
  710.  
  711.     
  712.     def uid(self, command, *args):
  713.         '''Execute "command arg ..." with messages identified by UID,
  714.                 rather than message number.
  715.  
  716.         (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
  717.  
  718.         Returns response appropriate to \'command\'.
  719.         '''
  720.         command = command.upper()
  721.         if command not in Commands:
  722.             raise self.error('Unknown IMAP4 UID command: %s' % command)
  723.         command not in Commands
  724.         if self.state not in Commands[command]:
  725.             raise self.error('command %s illegal in state %s, only allowed in states %s' % (command, self.state, ', '.join(Commands[command])))
  726.         self.state not in Commands[command]
  727.         name = 'UID'
  728.         (typ, dat) = self._simple_command(name, command, *args)
  729.         if command in ('SEARCH', 'SORT'):
  730.             name = command
  731.         else:
  732.             name = 'FETCH'
  733.         return self._untagged_response(typ, dat, name)
  734.  
  735.     
  736.     def unsubscribe(self, mailbox):
  737.         '''Unsubscribe from old mailbox.
  738.  
  739.         (typ, [data]) = <instance>.unsubscribe(mailbox)
  740.         '''
  741.         return self._simple_command('UNSUBSCRIBE', mailbox)
  742.  
  743.     
  744.     def xatom(self, name, *args):
  745.         """Allow simple extension commands
  746.                 notified by server in CAPABILITY response.
  747.  
  748.         Assumes command is legal in current state.
  749.  
  750.         (typ, [data]) = <instance>.xatom(name, arg, ...)
  751.  
  752.         Returns response appropriate to extension command `name'.
  753.         """
  754.         name = name.upper()
  755.         if name not in Commands:
  756.             Commands[name] = (self.state,)
  757.         
  758.         return self._simple_command(name, *args)
  759.  
  760.     
  761.     def _append_untagged(self, typ, dat):
  762.         if dat is None:
  763.             dat = ''
  764.         
  765.         ur = self.untagged_responses
  766.         if self.debug >= 5:
  767.             self._mesg('untagged_responses[%s] %s += ["%s"]' % (typ, len(ur.get(typ, '')), dat))
  768.         
  769.         if typ in ur:
  770.             ur[typ].append(dat)
  771.         else:
  772.             ur[typ] = [
  773.                 dat]
  774.  
  775.     
  776.     def _check_bye(self):
  777.         bye = self.untagged_responses.get('BYE')
  778.         if bye:
  779.             raise self.abort(bye[-1])
  780.         bye
  781.  
  782.     
  783.     def _command(self, name, *args):
  784.         if self.state not in Commands[name]:
  785.             self.literal = None
  786.             raise self.error('command %s illegal in state %s, only allowed in states %s' % (name, self.state, ', '.join(Commands[name])))
  787.         self.state not in Commands[name]
  788.         for typ in ('OK', 'NO', 'BAD'):
  789.             if typ in self.untagged_responses:
  790.                 del self.untagged_responses[typ]
  791.                 continue
  792.         
  793.         if 'READ-ONLY' in self.untagged_responses and not (self.is_readonly):
  794.             raise self.readonly('mailbox status changed to READ-ONLY')
  795.         not (self.is_readonly)
  796.         tag = self._new_tag()
  797.         data = '%s %s' % (tag, name)
  798.         for arg in args:
  799.             if arg is None:
  800.                 continue
  801.             
  802.             data = '%s %s' % (data, self._checkquote(arg))
  803.         
  804.         literal = self.literal
  805.         if literal is not None:
  806.             self.literal = None
  807.             if type(literal) is type(self._command):
  808.                 literator = literal
  809.             else:
  810.                 literator = None
  811.                 data = '%s {%s}' % (data, len(literal))
  812.         
  813.         if self.debug >= 4:
  814.             self._mesg('> %s' % data)
  815.         else:
  816.             self._log('> %s' % data)
  817.         
  818.         try:
  819.             self.send('%s%s' % (data, CRLF))
  820.         except (socket.error, OSError):
  821.             val = None
  822.             raise self.abort('socket error: %s' % val)
  823.  
  824.         if literal is None:
  825.             return tag
  826.         while None:
  827.             while self._get_response():
  828.                 if self.tagged_commands[tag]:
  829.                     return tag
  830.                 continue
  831.                 self.tagged_commands[tag]
  832.             if literator:
  833.                 literal = literator(self.continuation_response)
  834.             
  835.             if self.debug >= 4:
  836.                 self._mesg('write literal size %s' % len(literal))
  837.             
  838.             
  839.             try:
  840.                 self.send(literal)
  841.                 self.send(CRLF)
  842.             except (socket.error, OSError):
  843.                 val = None
  844.                 raise self.abort('socket error: %s' % val)
  845.  
  846.             if not literator:
  847.                 break
  848.                 continue
  849.             continue
  850.             return tag
  851.  
  852.     
  853.     def _command_complete(self, name, tag):
  854.         self._check_bye()
  855.         
  856.         try:
  857.             (typ, data) = self._get_tagged_response(tag)
  858.         except self.abort:
  859.             val = None
  860.             raise self.abort('command: %s => %s' % (name, val))
  861.         except self.error:
  862.             val = None
  863.             raise self.error('command: %s => %s' % (name, val))
  864.  
  865.         self._check_bye()
  866.         if typ == 'BAD':
  867.             raise self.error('%s command error: %s %s' % (name, typ, data))
  868.         typ == 'BAD'
  869.         return (typ, data)
  870.  
  871.     
  872.     def _get_response(self):
  873.         resp = self._get_line()
  874.         if self._match(self.tagre, resp):
  875.             tag = self.mo.group('tag')
  876.             if tag not in self.tagged_commands:
  877.                 raise self.abort('unexpected tagged response: %s' % resp)
  878.             tag not in self.tagged_commands
  879.             typ = self.mo.group('type')
  880.             dat = self.mo.group('data')
  881.             self.tagged_commands[tag] = (typ, [
  882.                 dat])
  883.         else:
  884.             dat2 = None
  885.             if not self._match(Untagged_response, resp):
  886.                 if self._match(Untagged_status, resp):
  887.                     dat2 = self.mo.group('data2')
  888.                 
  889.             
  890.             if self.mo is None:
  891.                 if self._match(Continuation, resp):
  892.                     self.continuation_response = self.mo.group('data')
  893.                     return None
  894.                 raise self.abort("unexpected response: '%s'" % resp)
  895.             self.mo is None
  896.             typ = self.mo.group('type')
  897.             dat = self.mo.group('data')
  898.             if dat is None:
  899.                 dat = ''
  900.             
  901.             if dat2:
  902.                 dat = dat + ' ' + dat2
  903.             
  904.             while self._match(Literal, dat):
  905.                 size = int(self.mo.group('size'))
  906.                 if self.debug >= 4:
  907.                     self._mesg('read literal size %s' % size)
  908.                 
  909.                 data = self.read(size)
  910.                 self._append_untagged(typ, (dat, data))
  911.                 dat = self._get_line()
  912.             self._append_untagged(typ, dat)
  913.         if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
  914.             self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  915.         
  916.         if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
  917.             self._mesg('%s response: %s' % (typ, dat))
  918.         
  919.         return resp
  920.  
  921.     
  922.     def _get_tagged_response(self, tag):
  923.         while None:
  924.             result = self.tagged_commands[tag]
  925.             if result is not None:
  926.                 del self.tagged_commands[tag]
  927.                 return result
  928.             
  929.             try:
  930.                 self._get_response()
  931.             continue
  932.             except self.abort:
  933.                 result is not None
  934.                 val = result is not None
  935.                 if self.debug >= 1:
  936.                     self.print_log()
  937.                 
  938.                 raise 
  939.                 continue
  940.             
  941.  
  942.             return None
  943.  
  944.     
  945.     def _get_line(self):
  946.         line = self.readline()
  947.         if not line:
  948.             raise self.abort('socket error: EOF')
  949.         line
  950.         line = line[:-2]
  951.         if self.debug >= 4:
  952.             self._mesg('< %s' % line)
  953.         else:
  954.             self._log('< %s' % line)
  955.         return line
  956.  
  957.     
  958.     def _match(self, cre, s):
  959.         self.mo = cre.match(s)
  960.         if self.mo is not None and self.debug >= 5:
  961.             self._mesg("\tmatched r'%s' => %r" % (cre.pattern, self.mo.groups()))
  962.         
  963.         return self.mo is not None
  964.  
  965.     
  966.     def _new_tag(self):
  967.         tag = '%s%s' % (self.tagpre, self.tagnum)
  968.         self.tagnum = self.tagnum + 1
  969.         self.tagged_commands[tag] = None
  970.         return tag
  971.  
  972.     
  973.     def _checkquote(self, arg):
  974.         if type(arg) is not type(''):
  975.             return arg
  976.         if len(arg) >= 2 and (arg[0], arg[-1]) in (('(', ')'), ('"', '"')):
  977.             return arg
  978.         if arg and self.mustquote.search(arg) is None:
  979.             return arg
  980.         return self._quote(arg)
  981.  
  982.     
  983.     def _quote(self, arg):
  984.         arg = arg.replace('\\', '\\\\')
  985.         arg = arg.replace('"', '\\"')
  986.         return '"%s"' % arg
  987.  
  988.     
  989.     def _simple_command(self, name, *args):
  990.         return self._command_complete(name, self._command(name, *args))
  991.  
  992.     
  993.     def _untagged_response(self, typ, dat, name):
  994.         if typ == 'NO':
  995.             return (typ, dat)
  996.         if name not in self.untagged_responses:
  997.             return (typ, [
  998.                 None])
  999.         data = self.untagged_responses.pop(name)
  1000.         return (typ, data)
  1001.  
  1002.     
  1003.     def _mesg(self, s, secs = None):
  1004.         if secs is None:
  1005.             secs = time.time()
  1006.         
  1007.         tm = time.strftime('%M:%S', time.localtime(secs))
  1008.         sys.stderr.write('  %s.%02d %s\n' % (tm, secs * 100 % 100, s))
  1009.         sys.stderr.flush()
  1010.  
  1011.     
  1012.     def _dump_ur(self, dict):
  1013.         l = dict.items()
  1014.         if not l:
  1015.             return None
  1016.         t = '\n\t\t'
  1017.         l = map((lambda x: if not x[1][0] or '" "'.join(x[1]):
  1018. pass'%s: "%s"' % (x[0], '')), l)
  1019.         self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
  1020.  
  1021.     
  1022.     def _log(self, line):
  1023.         self._cmd_log[self._cmd_log_idx] = (line, time.time())
  1024.         self._cmd_log_idx += 1
  1025.         if self._cmd_log_idx >= self._cmd_log_len:
  1026.             self._cmd_log_idx = 0
  1027.         
  1028.  
  1029.     
  1030.     def print_log(self):
  1031.         self._mesg('last %d IMAP4 interactions:' % len(self._cmd_log))
  1032.         i = self._cmd_log_idx
  1033.         n = self._cmd_log_len
  1034.         while n:
  1035.             
  1036.             try:
  1037.                 self._mesg(*self._cmd_log[i])
  1038.             except:
  1039.                 pass
  1040.  
  1041.             i += 1
  1042.             if i >= self._cmd_log_len:
  1043.                 i = 0
  1044.             
  1045.             n -= 1
  1046.  
  1047.  
  1048.  
  1049. try:
  1050.     import ssl
  1051. except ImportError:
  1052.     pass
  1053.  
  1054.  
  1055. class IMAP4_SSL(IMAP4):
  1056.     """IMAP4 client class over SSL connection
  1057.  
  1058.         Instantiate with: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
  1059.  
  1060.                 host - host's name (default: localhost);
  1061.                 port - port number (default: standard IMAP4 SSL port).
  1062.                 keyfile - PEM formatted file that contains your private key (default: None);
  1063.                 certfile - PEM formatted certificate chain file (default: None);
  1064.  
  1065.         for more documentation see the docstring of the parent class IMAP4.
  1066.         """
  1067.     
  1068.     def __init__(self, host = '', port = IMAP4_SSL_PORT, keyfile = None, certfile = None):
  1069.         self.keyfile = keyfile
  1070.         self.certfile = certfile
  1071.         IMAP4.__init__(self, host, port)
  1072.  
  1073.     
  1074.     def open(self, host = '', port = IMAP4_SSL_PORT):
  1075.         '''Setup connection to remote server on "host:port".
  1076.                 (default: localhost:standard IMAP4 SSL port).
  1077.             This connection will be used by the routines:
  1078.                 read, readline, send, shutdown.
  1079.             '''
  1080.         self.host = host
  1081.         self.port = port
  1082.         self.sock = socket.create_connection((host, port))
  1083.         self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
  1084.  
  1085.     
  1086.     def read(self, size):
  1087.         """Read 'size' bytes from remote."""
  1088.         chunks = []
  1089.         read = 0
  1090.         while read < size:
  1091.             data = self.sslobj.read(min(size - read, 16384))
  1092.             read += len(data)
  1093.             chunks.append(data)
  1094.         return ''.join(chunks)
  1095.  
  1096.     
  1097.     def readline(self):
  1098.         '''Read line from remote.'''
  1099.         line = []
  1100.         while None:
  1101.             char = self.sslobj.read(1)
  1102.             if char == '\n':
  1103.                 return ''.join(line)
  1104.             continue
  1105.             return None
  1106.  
  1107.     
  1108.     def send(self, data):
  1109.         '''Send data to remote.'''
  1110.         bytes = len(data)
  1111.         while bytes > 0:
  1112.             sent = self.sslobj.write(data)
  1113.             if sent == bytes:
  1114.                 break
  1115.             
  1116.             data = data[sent:]
  1117.             bytes = bytes - sent
  1118.  
  1119.     
  1120.     def shutdown(self):
  1121.         '''Close I/O established in "open".'''
  1122.         self.sock.close()
  1123.  
  1124.     
  1125.     def socket(self):
  1126.         '''Return socket instance used to connect to IMAP4 server.
  1127.  
  1128.             socket = <instance>.socket()
  1129.             '''
  1130.         return self.sock
  1131.  
  1132.     
  1133.     def ssl(self):
  1134.         '''Return SSLObject instance used to communicate with the IMAP4 server.
  1135.  
  1136.             ssl = ssl.wrap_socket(<instance>.socket)
  1137.             '''
  1138.         return self.sslobj
  1139.  
  1140.  
  1141. __all__.append('IMAP4_SSL')
  1142.  
  1143. class IMAP4_stream(IMAP4):
  1144.     '''IMAP4 client class over a stream
  1145.  
  1146.     Instantiate with: IMAP4_stream(command)
  1147.  
  1148.             where "command" is a string that can be passed to os.popen2()
  1149.  
  1150.     for more documentation see the docstring of the parent class IMAP4.
  1151.     '''
  1152.     
  1153.     def __init__(self, command):
  1154.         self.command = command
  1155.         IMAP4.__init__(self)
  1156.  
  1157.     
  1158.     def open(self, host = None, port = None):
  1159.         '''Setup a stream connection.
  1160.         This connection will be used by the routines:
  1161.             read, readline, send, shutdown.
  1162.         '''
  1163.         self.host = None
  1164.         self.port = None
  1165.         self.sock = None
  1166.         self.file = None
  1167.         (self.writefile, self.readfile) = os.popen2(self.command)
  1168.  
  1169.     
  1170.     def read(self, size):
  1171.         """Read 'size' bytes from remote."""
  1172.         return self.readfile.read(size)
  1173.  
  1174.     
  1175.     def readline(self):
  1176.         '''Read line from remote.'''
  1177.         return self.readfile.readline()
  1178.  
  1179.     
  1180.     def send(self, data):
  1181.         '''Send data to remote.'''
  1182.         self.writefile.write(data)
  1183.         self.writefile.flush()
  1184.  
  1185.     
  1186.     def shutdown(self):
  1187.         '''Close I/O established in "open".'''
  1188.         self.readfile.close()
  1189.         self.writefile.close()
  1190.  
  1191.  
  1192.  
  1193. class _Authenticator:
  1194.     '''Private class to provide en/decoding
  1195.             for base64-based authentication conversation.
  1196.     '''
  1197.     
  1198.     def __init__(self, mechinst):
  1199.         self.mech = mechinst
  1200.  
  1201.     
  1202.     def process(self, data):
  1203.         ret = self.mech(self.decode(data))
  1204.         if ret is None:
  1205.             return '*'
  1206.         return self.encode(ret)
  1207.  
  1208.     
  1209.     def encode(self, inp):
  1210.         oup = ''
  1211.         while inp:
  1212.             if len(inp) > 48:
  1213.                 t = inp[:48]
  1214.                 inp = inp[48:]
  1215.             else:
  1216.                 t = inp
  1217.                 inp = ''
  1218.             e = binascii.b2a_base64(t)
  1219.             if e:
  1220.                 oup = oup + e[:-1]
  1221.                 continue
  1222.         return oup
  1223.  
  1224.     
  1225.     def decode(self, inp):
  1226.         if not inp:
  1227.             return ''
  1228.         return binascii.a2b_base64(inp)
  1229.  
  1230.  
  1231. Mon2num = {
  1232.     'Jan': 1,
  1233.     'Feb': 2,
  1234.     'Mar': 3,
  1235.     'Apr': 4,
  1236.     'May': 5,
  1237.     'Jun': 6,
  1238.     'Jul': 7,
  1239.     'Aug': 8,
  1240.     'Sep': 9,
  1241.     'Oct': 10,
  1242.     'Nov': 11,
  1243.     'Dec': 12 }
  1244.  
  1245. def Internaldate2tuple(resp):
  1246.     '''Convert IMAP4 INTERNALDATE to UT.
  1247.  
  1248.     Returns Python time module tuple.
  1249.     '''
  1250.     mo = InternalDate.match(resp)
  1251.     if not mo:
  1252.         return None
  1253.     mon = Mon2num[mo.group('mon')]
  1254.     zonen = mo.group('zonen')
  1255.     day = int(mo.group('day'))
  1256.     year = int(mo.group('year'))
  1257.     hour = int(mo.group('hour'))
  1258.     min = int(mo.group('min'))
  1259.     sec = int(mo.group('sec'))
  1260.     zoneh = int(mo.group('zoneh'))
  1261.     zonem = int(mo.group('zonem'))
  1262.     zone = (zoneh * 60 + zonem) * 60
  1263.     if zonen == '-':
  1264.         zone = -zone
  1265.     
  1266.     tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  1267.     utc = time.mktime(tt)
  1268.     lt = time.localtime(utc)
  1269.     if time.daylight and lt[-1]:
  1270.         zone = zone + time.altzone
  1271.     else:
  1272.         zone = zone + time.timezone
  1273.     return time.localtime(utc - zone)
  1274.  
  1275.  
  1276. def Int2AP(num):
  1277.     '''Convert integer to A-P string representation.'''
  1278.     val = ''
  1279.     AP = 'ABCDEFGHIJKLMNOP'
  1280.     num = int(abs(num))
  1281.     while num:
  1282.         (num, mod) = divmod(num, 16)
  1283.         val = AP[mod] + val
  1284.     return val
  1285.  
  1286.  
  1287. def ParseFlags(resp):
  1288.     '''Convert IMAP4 flags response to python tuple.'''
  1289.     mo = Flags.match(resp)
  1290.     if not mo:
  1291.         return ()
  1292.     return tuple(mo.group('flags').split())
  1293.  
  1294.  
  1295. def Time2Internaldate(date_time):
  1296.     '''Convert \'date_time\' to IMAP4 INTERNALDATE representation.
  1297.  
  1298.     Return string in form: \'"DD-Mmm-YYYY HH:MM:SS +HHMM"\'
  1299.     '''
  1300.     if isinstance(date_time, (int, float)):
  1301.         tt = time.localtime(date_time)
  1302.     elif isinstance(date_time, (tuple, time.struct_time)):
  1303.         tt = date_time
  1304.     elif isinstance(date_time, str) and (date_time[0], date_time[-1]) == ('"', '"'):
  1305.         return date_time
  1306.     raise ValueError('date_time not of a known type')
  1307.     dt = time.strftime('%d-%b-%Y %H:%M:%S', tt)
  1308.     if dt[0] == '0':
  1309.         dt = ' ' + dt[1:]
  1310.     
  1311.     if time.daylight and tt[-1]:
  1312.         zone = -(time.altzone)
  1313.     else:
  1314.         zone = -(time.timezone)
  1315.     return '"' + dt + ' %+03d%02d' % divmod(zone // 60, 60) + '"'
  1316.  
  1317. if __name__ == '__main__':
  1318.     import getopt
  1319.     import getpass
  1320.     
  1321.     try:
  1322.         (optlist, args) = getopt.getopt(sys.argv[1:], 'd:s:')
  1323.     except getopt.error:
  1324.         val = None
  1325.         (optlist, args) = ((), ())
  1326.  
  1327.     stream_command = None
  1328.     for opt, val in optlist:
  1329.         if opt == '-d':
  1330.             Debug = int(val)
  1331.         elif opt == '-s':
  1332.             stream_command = val
  1333.             if not args:
  1334.                 args = (stream_command,)
  1335.             
  1336.         
  1337.     
  1338.     if not args:
  1339.         args = ('',)
  1340.     
  1341.     host = args[0]
  1342.     USER = getpass.getuser()
  1343.     if not host:
  1344.         pass
  1345.     PASSWD = getpass.getpass('IMAP password for %s on %s: ' % (USER, 'localhost'))
  1346.     test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)sdata...%(lf)s' % {
  1347.         'user': USER,
  1348.         'lf': '\n' }
  1349.     test_seq1 = (('login', (USER, PASSWD)), ('create', ('/tmp/xxx 1',)), ('rename', ('/tmp/xxx 1', '/tmp/yyy')), ('CREATE', ('/tmp/yyz 2',)), ('append', ('/tmp/yyz 2', None, None, test_mesg)), ('list', ('/tmp', 'yy*')), ('select', ('/tmp/yyz 2',)), ('search', (None, 'SUBJECT', 'test')), ('fetch', ('1', '(FLAGS INTERNALDATE RFC822)')), ('store', ('1', 'FLAGS', '(\\Deleted)')), ('namespace', ()), ('expunge', ()), ('recent', ()), ('close', ()))
  1350.     test_seq2 = (('select', ()), ('response', ('UIDVALIDITY',)), ('uid', ('SEARCH', 'ALL')), ('response', ('EXISTS',)), ('append', (None, None, None, test_mesg)), ('recent', ()), ('logout', ()))
  1351.     
  1352.     def run(cmd, args):
  1353.         M._mesg('%s %s' % (cmd, args))
  1354.         (typ, dat) = getattr(M, cmd)(*args)
  1355.         M._mesg('%s => %s %s' % (cmd, typ, dat))
  1356.         if typ == 'NO':
  1357.             raise dat[0]
  1358.         typ == 'NO'
  1359.         return dat
  1360.  
  1361.     
  1362.     try:
  1363.         if stream_command:
  1364.             M = IMAP4_stream(stream_command)
  1365.         else:
  1366.             M = IMAP4(host)
  1367.         if M.state == 'AUTH':
  1368.             test_seq1 = test_seq1[1:]
  1369.         
  1370.         M._mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  1371.         M._mesg('CAPABILITIES = %r' % (M.capabilities,))
  1372.         for cmd, args in test_seq1:
  1373.             run(cmd, args)
  1374.         
  1375.         for ml in run('list', ('/tmp/', 'yy%')):
  1376.             mo = re.match('.*"([^"]+)"$', ml)
  1377.             if mo:
  1378.                 path = mo.group(1)
  1379.             else:
  1380.                 path = ml.split()[-1]
  1381.             run('delete', (path,))
  1382.         
  1383.         for cmd, args in test_seq2:
  1384.             dat = run(cmd, args)
  1385.             if (cmd, args) != ('uid', ('SEARCH', 'ALL')):
  1386.                 continue
  1387.             
  1388.             uid = dat[-1].split()
  1389.             if not uid:
  1390.                 continue
  1391.             
  1392.             run('uid', ('FETCH', '%s' % uid[-1], '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  1393.         
  1394.         print '\nAll tests OK.'
  1395.     except:
  1396.         print '\nTests failed.'
  1397.         if not Debug:
  1398.             print '\nIf you would like to see debugging output,\ntry: %s -d5\n' % sys.argv[0]
  1399.         
  1400.         raise 
  1401.  
  1402.  
  1403.